package servlets;

import it.poste.il.compensatore.control.Integration;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Servlet implementation class HttpReceiver
 */
@WebServlet("/*")
public class HttpReceiver extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	Integration integrationImpl;

	public Integration getIntegrationImpl() {
		return integrationImpl;
	}

	public void setIntegrationImpl(Integration integrationImpl) {
		this.integrationImpl = integrationImpl;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("POST Partito!");
		
		String url = "http://localhost:8181/CompensatorePoste/Stub";
		System.out.println("URL: " + url);
		
		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
		    while ((line = reader.readLine()) != null)
		    	jb.append(line);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String soapRequest = jb.toString();
		System.out.println("Messaggio: " + soapRequest);

		String soapAction = request.getHeader("SOAPAction");
		System.out.println("SOAP Action: " + soapAction);
		
		System.out.println(" --- Chiamata all'IntegrationImpl --- ");
		WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());    
		Integration integrationImpl= (Integration) springContext.getBean("IntegrationImpl");
		String result = null;
		try {
			result = integrationImpl.syncMsg(soapRequest);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
		}
		
//		Invia la response a SDP
		ServletOutputStream respStream = response.getOutputStream();
		respStream.write(result.getBytes());
		respStream.close();

		
	}

}
